package biz;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import vo.Cart;
import vo.Item;

public class CartBiz {
	public void addCart(HttpServletRequest request, Item item){
		HttpSession session=request.getSession();
		ArrayList<Cart> cartList=(ArrayList<Cart>)session.getAttribute("cartList"); //한번만 만들기 위해서..
		
		//목록 하나가 있는 cart 객체를 ArrayList로 받아옴
		if(cartList==null){
			cartList = new ArrayList<Cart>();
		}
		
		Cart cart=  null;
		boolean newCart=  true;
		for(int i=0; i<cartList.size(); i++){
			cart = cartList.get(i);
			if(item.getName().equals(cart.getName())){ //지금 선택한 상품이 cart에 있는 상품이면
				newCart = false;
				cart.setQuantity(cart.getQuantity()+1);//수량만 증가시킴				
			}//if
		}//for
		
		if(newCart){//cart에 상품이 추가되어 있지 않을때는..
			cart = new Cart();
			cart.setImage(item.getUrl());
			cart.setName(item.getName());
			cart.setPrice(item.getPrice());
			cart.setQuantity(1); //무조건 1이 들어감.
			cartList.add(cart);
			
		}
		//여기서 세션에 저장한다..
		session.setAttribute("cartList", cartList);
	}
	
	public ArrayList<Cart> getCartList(HttpServletRequest request){
		HttpSession session=request.getSession();
		ArrayList<Cart> cartList = (ArrayList<Cart>)session.getAttribute("cartList");
		return cartList;
	}
	
	public void removeCartItem(HttpServletRequest request, String[ ] names){
		HttpSession session = request.getSession();
		ArrayList<Cart> cartList = (ArrayList<Cart>)session.getAttribute("cartList");
		for(int i=0; i<names.length; i++){
			for(int j=0; j<cartList.size(); j++){
				if(names[i].equals(cartList.get(j).getName())){
					cartList.remove(cartList.get(j));
				}
			}
		}
	}
	
	public void upCartQty(HttpServletRequest request, String name){
		HttpSession session=  request.getSession();
		ArrayList<Cart> cartList = (ArrayList<Cart>)session.getAttribute("cartList");
		for(int i=0; i<cartList.size(); i++){
			if(cartList.get(i).getName().equals(name)){
				cartList.get(i).setQuantity(cartList.get(i).getQuantity()+1);
			}
		}
	}
	
	public void downCartQty(HttpServletRequest request, String name){
		HttpSession session=  request.getSession();
		ArrayList<Cart> cartList = (ArrayList<Cart>)session.getAttribute("cartList");
		for(int i=0; i<cartList.size(); i++){
			if(cartList.get(i).getName().equals(name)){
				cartList.get(i).setQuantity(cartList.get(i).getQuantity()-1);
			}
		}
	}
	
}













